<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人设置</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.3/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="css/setting.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        :root {
            --primary-color: #fff9e6;
            --primary-hover: #FFD700;
            --primary-active: #FFF8DC;
            --text-color: #333;
            --button-color: #FFD700;
        }

        body {
            margin: 0;
            padding: 0;
            background: var(--primary-color);
            font-family: Arial, sans-serif;
        }

        .container {
            max-width: 1200px;
            margin: 20px auto;
            padding: 0 20px;
            display: flex;
            gap: 20px;
        }

        /* 左侧导航栏 */
        .nav-sidebar {
            width: 200px;
            background: white;
            border-radius: 8px;
            padding: 20px 0;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .nav-item {
            padding: 15px 20px;
            cursor: pointer;
            color: var(--text-color);
            transition: all 0.3s;
        }

        .nav-item:hover {
            background: var(--primary-color);
            color: var(--text-color);
        }

        .nav-item.active {
            background: var(--primary-active);
            color: var(--text-color);
            border-left: 3px solid var(--primary-hover);
        }

        .nav-item i {
            margin-right: 10px;
            width: 20px;
            text-align: center;
        }

        /* 右侧内容区 */
        .content {
            flex: 1;
            background: white;
            border-radius: 8px;
            padding: 30px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .section {
            display: none;
        }

        .section.active {
            display: block;
        }

        .section-title {
            font-size: 20px;
            color: var(--text-color);
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }

        /* 表单样式 */
        .form-group {
            margin-bottom: 20px;
        }

        .form-label {
            display: block;
            margin-bottom: 8px;
            color: var(--text-color);
        }

        .form-input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        .form-input:focus {
            border-color: var(--primary-hover);
            outline: none;
            box-shadow: 0 0 0 2px rgba(255, 215, 0, 0.2);
        }

        /* 头像上传 */
        .avatar-upload {
            display: flex;
            align-items: center;
            gap: 20px;
            margin-bottom: 20px;
        }

        .avatar-preview {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            overflow: hidden;
            border: 3px solid var(--primary-color);
        }

        .avatar-preview img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        /* 收货地址列表 */
        .address-list {
            margin-bottom: 20px;
        }

        .address-item {
            padding: 20px;
            border: 1px solid #e8e8e8;
            border-radius: 8px;
            margin-bottom: 15px;
            position: relative;
            transition: all 0.3s;
        }

        .address-item:hover {
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .address-item.default {
            border: 2px solid var(--primary-hover);
        }

        .default-tag {
            position: absolute;
            top: 10px;
            right: 10px;
            background: var(--primary-color);
            color: var(--text-color);
            padding: 3px 8px;
            border-radius: 4px;
            font-size: 12px;
        }

        .address-info {
            margin-bottom: 15px;
        }

        .recipient-info {
            margin-bottom: 8px;
            font-size: 16px;
            font-weight: bold;
        }

        .recipient-info .name {
            margin-right: 15px;
        }

        .recipient-info .phone {
            color: #666;
            font-weight: normal;
        }

        .address-text {
            color: #666;
            line-height: 1.5;
        }

        .address-actions {
            display: flex;
            gap: 10px;
            margin-top: 15px;
            border-top: 1px solid #f0f0f0;
            padding-top: 15px;
        }

        .address-actions button {
            padding: 5px 15px;
            border-radius: 4px;
            border: 1px solid #ddd;
            background: white;
            color: var(--text-color);
            cursor: pointer;
            transition: all 0.3s;
        }

        .address-actions button:hover {
            background: var(--primary-color);
            border-color: var(--primary-hover);
        }

        /* 按钮样式 */
        .btn {
            padding: 8px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
        }

        .btn-primary {
            background: var(--button-color);
            color: var(--text-color);
            border: 1px solid var(--primary-hover);
        }

        .btn-secondary {
            background: #f5f5f5;
            color: var(--text-color);
            border: 1px solid #ddd;
        }

        .btn:hover {
            background: var(--primary-hover);
            opacity: 0.9;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
        }

        .modal.show {
            display: block;
        }

        .modal-dialog {
            position: relative;
            width: 500px;
            margin: 60px auto;
            background: white;
            border-radius: 8px;
            box-shadow: 0 3px 15px rgba(0, 0, 0, 0.2);
        }

        .modal-content {
            padding: 20px;
        }

        .modal-header {
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-title {
            font-size: 18px;
            font-weight: bold;
        }

        .modal-close {
            cursor: pointer;
            font-size: 24px;
            color: #666;
        }

        .modal-body {
            padding: 20px 0;
        }

        .modal-footer {
            padding-top: 15px;
            border-top: 1px solid #eee;
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }

        .close {
            float: right;
            font-size: 1.5rem;
            font-weight: 700;
            line-height: 1;
            color: #000;
            text-shadow: 0 1px 0 #fff;
            opacity: .5;
            padding: 0;
            background-color: transparent;
            border: 0;
            appearance: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 左侧导航 -->
        <div class="nav-sidebar">
            <div class="nav-item active" data-section="profile">
                <i class="fas fa-user"></i>个人信息
            </div>
            <div class="nav-item" data-section="address">
                <i class="fas fa-map-marker-alt"></i>收货地址
            </div>
            <div class="nav-item" data-section="password">
                <i class="fas fa-lock"></i>修改密码
            </div>
        </div>

        <!-- 右侧内容区 -->
        <div class="content">
            <!-- 个人信息模块 -->
            <div class="section active" id="profile">
                <h2 class="section-title">个人信息</h2>
                <div class="avatar-upload">
                    <div class="avatar-preview">
                        <img src="" id="currentAvatar" alt="头像">
                    </div>
                    <div>
                        <input type="file" id="avatarInput" accept="image/*" style="display: none;">
                        <button class="btn btn-secondary" onclick="document.getElementById('avatarInput').click()">
                            更换头像
                        </button>
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label">昵称</label>
                    <input type="text" class="form-input" id="nickname">
                </div>
                <div class="form-group">
                    <label class="form-label">手机号</label>
                    <input type="tel" class="form-input" id="phone">
                </div>
                <button class="btn btn-primary" onclick="saveProfile()">保存修改</button>
            </div>

            <!-- 收货地址模块 -->
            <div class="section" id="address">
                <h2 class="section-title">收货地址</h2>
                <!-- 添加地址按钮 -->
                <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addressModal">
                    添加新地址
                </button>

                <div class="address-list" id="addressList">
                    <!-- 地址列表将通过JS动态添加 -->
                </div>

                <!-- 添加地址模态框 -->
                <div class="modal" id="addressModal" tabindex="-1">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">添加新地址</h5>
                                <button type="button" class="close" data-dismiss="modal">&times;</button>
                            </div>
                            <div class="modal-body">
                                <div class="alert alert-info">
                                    <small>
                                        · 收货人：请填写真实姓名，方便快递员联系<br>
                                        · 手机号码：请填写真实的手机号码，保证快递员能联系到您<br>
                                        · 收货地址：请填写详细的收货地址，包括省市区、街道、门牌号等
                                    </small>
                                </div>
                                <form id="addressForm">
                                    <input type="hidden" id="addressId">
                                    <div class="form-group">
                                        <label>收货人</label>
                                        <input type="text" class="form-control" id="recipientName" required 
                                            placeholder="请填写收货人真实姓名">
                                    </div>
                                    <div class="form-group">
                                        <label>手机号码</label>
                                        <input type="tel" class="form-control" id="recipientPhone" required
                                            placeholder="请填写11位手机号码">
                                    </div>
                                    <div class="form-group">
                                        <label>详细地址</label>
                                        <textarea class="form-control" id="addressDetail" required
                                            placeholder="省市区街道，小区名称，楼栋号，门牌号等"></textarea>
                                    </div>
                                    <div class="form-check">
                                        <input type="checkbox" class="form-check-input" id="setDefault">
                                        <label class="form-check-label">设为默认地址</label>
                                    </div>
                                </form>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                                <button type="button" class="btn btn-primary" id="saveAddressBtn">保存</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 修改密码模块 -->
            <div class="section" id="password">
                <h2 class="section-title">修改密码</h2>
                <div class="form-group">
                    <label class="form-label">当前密码</label>
                    <input type="password" class="form-input" id="currentPassword">
                </div>
                <div class="form-group">
                    <label class="form-label">新密码</label>
                    <input type="password" class="form-input" id="newPassword">
                </div>
                <div class="form-group">
                    <label class="form-label">确认新密码</label>
                    <input type="password" class="form-input" id="confirmPassword">
                </div>
                <button class="btn btn-primary" onclick="changePassword()">修改密码</button>
            </div>
        </div>
    </div>

    <script>
        // 导航切换
        $('.nav-item').click(function() {
            $('.nav-item').removeClass('active');
            $(this).addClass('active');
            
            const section = $(this).data('section');
            $('.section').removeClass('active');
            $(`#${section}`).addClass('active');
        });

        // 模态框相关函数
        function showModal(modalId) {
            $(`#${modalId}`).addClass('show');
        }

        function closeModal(modalId) {
            $(`#${modalId}`).removeClass('show');
        }

        // 加载个人信息
        function loadProfile() {
            // 先显示一个默认头像
            $('#currentAvatar').attr('src', 'img/default-avatar.png');
            
            $.ajax({
                url: '/user/get-user',
                type: 'GET',
                success: function(response) {
                    if(response.state === 1) {
                        const user = response.data;
                        $('#nickname').val(user.nickname);
                        $('#phone').val(user.phone);
                        
                        // 异步加载头像
                        if (user.avatar) {
                            const avatarImg = new Image();
                            avatarImg.onload = function() {
                                $('#currentAvatar').attr('src', user.avatar);
                            };
                            avatarImg.onerror = function() {
                                console.log('头像加载失败，使用默认头像');
                            };
                            avatarImg.src = user.avatar;
                        }
                    }
                }
            });
        }

        // 保存个人信息
        function saveProfile() {
            const nickname = $('#nickname').val().trim();
            const phone = $('#phone').val().trim();
            
            if (!nickname) {
                alert('请输入昵称');
                return;
            }
            if (!phone) {
                alert('请输入手机号');
                return;
            }
            if (!/^1\d{10}$/.test(phone)) {
                alert('请输入正确的手机号格式');
                return;
            }

            const formData = new FormData();
            formData.append('nickname', nickname);
            formData.append('phone', phone);
            
            const avatarFile = $('#avatarInput')[0].files[0];
            if (avatarFile) {
                formData.append('avatar', avatarFile);
            }

            const saveBtn = $(event.target);  // 获取实际点击的按钮
            const originalText = saveBtn.text();
            saveBtn.prop('disabled', true).text('保存中...');

            $.ajax({
                url: '/user/update-info',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    if (response.state === 1) {
                        alert('保存成功');
                        loadProfile();
                        $('#avatarInput').val('');
                    } else {
                        alert(response.msg || '保存失败');
                    }
                },
                error: function() {
                    alert('保存失败，请稍后重试');
                },
                complete: function() {
                    saveBtn.prop('disabled', false).text(originalText);
                }
            });
        }

        // 保存收货地址
        function saveAddress() {
            const address = {
                id: $('#addressId').val() || null,
                recipientName: $('#recipientName').val().trim(),
                recipientPhone: $('#recipientPhone').val().trim(),
                address: $('#addressDetail').val().trim(),
                isDefault: $('#setDefault').is(':checked') ? 1 : 0
            };
            
            // 表单验证
            if (!address.recipientName) {
                alert('请输入收货人姓名');
                return;
            }
            if (!address.recipientPhone) {
                alert('请输入手机号码');
                return;
            }
            if (!/^1\d{10}$/.test(address.recipientPhone)) {
                alert('请输入正确的手机号格式');
                return;
            }
            if (!address.address) {
                alert('请输入详细地址');
                return;
            }
            
            const url = address.id ? '/user/update-address' : '/user/save-address';
            
            $.ajax({
                url: url,
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(address),
                success: function(response) {
                    if (response.state === 1) {
                        // 关闭模态框
                        closeModal('addressModal');
                        // 清空表单
                        resetAddressForm();
                        // 添加新地址到列表
                        if (!address.id) {
                            // 如果是新增地址，将返回的数据添加到列表
                            address.id = response.data.id; // 获取新地址的ID
                            appendAddressToList(address);
                        } else {
                            // 如果是更新地址，更新列表中的对应项
                            updateAddressInList(address);
                        }
                        alert(address.id ? '更新成功' : '添加成功');
                    } else {
                        alert(response.msg || (address.id ? '更新失败' : '添加失败'));
                    }
                },
                error: function() {
                    alert((address.id ? '更新' : '添加') + '失败，请稍后重试');
                }
            });
        }

        // 将新地址添加到列表
        function appendAddressToList(address) {
            const addressHtml = createAddressHtml(address);
            if (address.isDefault) {
                // 如果是默认地址，移除其他地址的默认标记
                $('.address-item').removeClass('default');
                $('.default-tag').remove();
                // 将新地址添加到列表最前面
                $('#addressList').prepend(addressHtml);
            } else {
                // 非默认地址添加到列表末尾
                $('#addressList').append(addressHtml);
            }
        }

        // 更新列表中的地址
        function updateAddressInList(address) {
            const addressHtml = createAddressHtml(address);
            const existingAddress = $(`#address-${address.id}`);
            if (address.isDefault) {
                // 如果设为默认地址，移除其他地址的默认标记
                $('.address-item').removeClass('default');
                $('.default-tag').remove();
            }
            if (existingAddress.length) {
                existingAddress.replaceWith(addressHtml);
            }
        }

        // 创建地址HTML
        function createAddressHtml(address) {
            return `
                <div class="address-item ${address.isDefault ? 'default' : ''}" id="address-${address.id}">
                    ${address.isDefault ? '<span class="default-tag">默认地址</span>' : ''}
                    <div class="address-info">
                        <div class="recipient-info">
                            <span class="name">收货人：${address.recipientName}</span>
                            <span class="phone">电话：${address.recipientPhone}</span>
                        </div>
                        <div class="address-text">
                            <span class="label">收货地址：</span>${address.address}
                        </div>
                    </div>
                    <div class="address-actions">
                        <button onclick="editAddress(${JSON.stringify(address).replace(/"/g, '&quot;')})">
                            <i class="fas fa-edit"></i> 编辑
                        </button>
                        <button onclick="deleteAddress(${address.id})">
                            <i class="fas fa-trash"></i> 删除
                        </button>
                        ${!address.isDefault ? `
                            <button onclick="setDefaultAddress(${address.id})">
                                <i class="fas fa-star"></i> 设为默认
                            </button>
                        ` : ''}
                    </div>
                </div>
            `;
        }

        // 删除地址后实时更新列表
        function deleteAddress(addressId) {
            if (confirm('确定要删除这个地址吗？')) {
                $.ajax({
                    url: `/user/delete-address/${addressId}`,
                    type: 'POST',
                    success: function(response) {
                        if (response.state === 1) {
                            // 直接从DOM中移除该地址
                            $(`#address-${addressId}`).remove();
                            // 如果没有地址了，显示空状态
                            if ($('.address-item').length === 0) {
                                $('#addressList').html(`
                                    <div class="no-address">
                                        <p style="text-align: center; color: #999; padding: 30px;">
                                            暂无收货地址，请添加新地址
                                        </p>
                                    </div>
                                `);
                            }
                            alert('删除成功');
                        } else {
                            alert(response.msg || '删除失败');
                        }
                    },
                    error: function() {
                        alert('删除失败，请稍后重试');
                    }
                });
            }
        }

        // 设为默认地址后实时更新列表
        function setDefaultAddress(addressId) {
            $.ajax({
                url: '/user/update-address',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    id: addressId,
                    isDefault: 1
                }),
                success: function(response) {
                    if (response.state === 1) {
                        // 移除所有地址的默认标记和"设为默认"按钮
                        $('.address-item').each(function() {
                            const $item = $(this);
                            $item.removeClass('default');
                            $item.find('.default-tag').remove();
                            // 为所有地址添加"设为默认"按钮
                            const id = $item.attr('id').replace('address-', '');
                            const $actions = $item.find('.address-actions');
                            if (!$actions.find('button:contains("设为默认")').length) {
                                $actions.append(`
                                    <button onclick="setDefaultAddress(${id})">
                                        <i class="fas fa-star"></i> 设为默认
                                    </button>
                                `);
                            }
                        });

                        // 为当前地址添加默认标记并移除其"设为默认"按钮
                        const currentAddress = $(`#address-${addressId}`);
                        currentAddress.addClass('default');
                        currentAddress.prepend('<span class="default-tag">默认地址</span>');
                        currentAddress.find('button:contains("设为默认")').remove();

                        // 将默认地址移到最前面
                        $('#addressList').prepend(currentAddress);
                        alert('设置成功');
                    } else {
                        alert(response.msg || '设置失败');
                    }
                },
                error: function() {
                    alert('设置失败，请稍后重试');
                }
            });
        }

        // 修改密码
        function changePassword() {
            const currentPassword = $('#currentPassword').val();
            const newPassword = $('#newPassword').val();
            const confirmPassword = $('#confirmPassword').val();

            if(newPassword !== confirmPassword) {
                alert('两次输入的新密码不一致');
                return;
            }

            $.ajax({
                url: '/user/change-password',
                type: 'POST',
                data: {
                    currentPassword: currentPassword,
                    newPassword: newPassword
                },
                success: function(response) {
                    if(response.state === 200) {
                        alert('密码修改成功，请重新登录');
                        location.href = 'login.html';
                    } else {
                        alert(response.msg);
                    }
                }
            });
        }

        // 退出登录
        function logout() {
            $.ajax({
                url: '/user/logout',
                type: 'POST',
                success: function(response) {
                    if(response.state === 1) {
                        // 跳转到登录页
                        location.href = 'login.html';
                    } else {
                        alert('退出失败，请重试');
                    }
                }
            });
        }

        // 加载收货地址列表
        function loadAddresses() {
            $.ajax({
                url: '/user/get-addresses',
                type: 'GET',
                success: function(response) {
                    if(response.state === 1) {
                        const addresses = response.data;
                        const addressList = $('#addressList');
                        addressList.empty();
                        
                        if (addresses && addresses.length > 0) {
                            addresses.forEach(address => {
                                appendAddressToList(address);
                            });
                        } else {
                            addressList.html(`
                                <div class="no-address">
                                    <p style="text-align: center; color: #999; padding: 30px;">
                                        暂无收货地址，请添加新地址
                                    </p>
                                </div>
                            `);
                        }
                    }
                }
            });
        }

        // 重置地址表单
        function resetAddressForm() {
            $('#addressForm')[0].reset();
            $('#addressId').val('');
            $('.modal-title').text('添加新地址');
        }

        // 编辑地址
        function editAddress(address) {
            $('.modal-title').text('编辑收货地址');
            $('#addressId').val(address.id);
            $('#recipientName').val(address.recipientName);
            $('#recipientPhone').val(address.recipientPhone);
            $('#addressDetail').val(address.address);
            $('#setDefault').prop('checked', address.isDefault === 1);
            showModal('addressModal');
        }

        // 页面加载完成后执行
        $(document).ready(function() {
            loadProfile();
            loadAddresses();
            
            // 绑定添加地址按钮点击事件
            $('[data-toggle="modal"]').click(function() {
                const target = $(this).data('target');
                showModal(target.substring(1)); // 移除开头的 #
                resetAddressForm();
            });
            
            // 绑定关闭按钮事件
            $('.close, .modal-close, [data-dismiss="modal"]').click(function() {
                const modal = $(this).closest('.modal');
                closeModal(modal.attr('id'));
            });
            
            // 绑定保存按钮事件
            $('#saveAddressBtn').click(function() {
                saveAddress();
            });

            // 绑定头像文件选择事件
            $('#avatarInput').change(function(e) {
                const file = e.target.files[0];
                if (file) {
                    if (!file.type.startsWith('image/')) {
                        alert('请选择图片文件');
                        this.value = '';
                        return;
                    }

                    if (file.size > 2 * 1024 * 1024) {
                        alert('图片大小不能超过2MB');
                        this.value = '';
                        return;
                    }

                    // 只预览，不自动保存
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        $('#currentAvatar').attr('src', e.target.result);
                    };
                    reader.readAsDataURL(file);
                }
            });

            // 点击空白处关闭模态框
            $(window).click(function(event) {
                if ($(event.target).hasClass('modal')) {
                    closeModal($(event.target).attr('id'));
                }
            });
        });
    </script>
</body>
</html> 